#!/bin/bash
# postinst script for cpu-scheduler

set -e

case "$1" in
    configure)
        # 设置启动脚本权限
        if [ -f /usr/bin/cpu-scheduler ]; then
            chmod 755 /usr/bin/cpu-scheduler
        fi
        
        # 更新桌面数据库
        if [ -x /usr/bin/update-desktop-database ]; then
            update-desktop-database /usr/share/applications/ >/dev/null 2>&1 || true
        fi
        
        # 更新图标缓存 - 加强处理
        # 确保图标目录存在
        if [ -d /usr/share/icons/hicolor ]; then
            # 强制更新图标缓存
            if [ -x /usr/bin/gtk-update-icon-cache ]; then
                gtk-update-icon-cache -f /usr/share/icons/hicolor >/dev/null 2>&1 || true
            elif [ -x /usr/bin/update-icon-caches ]; then
                update-icon-caches /usr/share/icons/hicolor >/dev/null 2>&1 || true
            fi
            
            # 如果上述命令都失败，尝试使用touch命令触发更新
            if [ -d /usr/share/icons/hicolor ]; then
                touch /usr/share/icons/hicolor >/dev/null 2>&1 || true
            fi
        fi
        
        # 重新加载PolicyKit规则
        if [ -x /usr/bin/pkill ]; then
            pkill -HUP polkitd || true
        fi
        
        # 创建默认配置文件
        if [ ! -f /etc/cpu-scheduler.conf ]; then
            cat > /etc/cpu-scheduler.conf << 'EOD'
[DEFAULT]
CHECK_INTERVAL = 10
HIGH_FREQ_THRESHOLD = 80
LOW_FREQ_THRESHOLD = 40
HIGH_TEMP_THRESHOLD = 60
LOW_TEMP_THRESHOLD = 40
SUSTAINED_PERIOD = 60
FREQ_REDUCTION = 25
FREQ_INCREASE = 25
LOG_FILE = /var/log/cpu-scheduler.log
ENABLE_TEMP_CONTROL = true
ENABLE_FREQ_CONTROL = true
EOD
        fi
        
        # 创建并启动服务
        if [ -f /usr/local/bin/cpu_scheduler.py ]; then
            # 创建服务文件
            cat > /etc/systemd/system/cpu-scheduler.service << 'EOD'
[Unit]
Description=CPU Scheduler Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/cpu_scheduler.py --service
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOD
            
            # 重载systemd配置
            systemctl daemon-reload >/dev/null 2>&1 || true
            
            # 启用并启动服务
            systemctl enable cpu-scheduler.service >/dev/null 2>&1 || true
            systemctl start cpu-scheduler.service >/dev/null 2>&1 || true
        fi
    ;;
esac

# 添加额外的图标缓存更新步骤，确保在不同环境下都能正确更新
if [ "$1" = "configure" ]; then
    # 尝试多种方式更新图标缓存
    for icon_updater in gtk-update-icon-cache update-icon-caches; do
        if command -v "$icon_updater" >/dev/null 2>&1; then
            "$icon_updater" /usr/share/icons/hicolor 2>/dev/null || true
            break
        fi
    done
    
    # 如果上述方法都失败，尝试使用xdg-icon-resource
    if command -v xdg-icon-resource >/dev/null 2>&1; then
        # 重新安装图标
        if [ -f /usr/share/icons/hicolor/48x48/apps/cpu-scheduler.png ]; then
            xdg-icon-resource install --size 48 --context apps /usr/share/icons/hicolor/48x48/apps/cpu-scheduler.png cpu-scheduler 2>/dev/null || true
        fi
    fi
fi

exit 0
